/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui.Ventas;

import javax.swing.JDialog;
import javax.swing.table.AbstractTableModel;
import java.util.Date;
import Controlador.Service.Ventas.GestionVentas;
import Controlador.Bean.Ventas.Cliente;
import Controlador.Bean.Ventas.LineaCotizacion;
import Controlador.Bean.Ventas.Cotizacion;
import Controlador.Service.Configuracion.GestionConfiguracion;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author Luis Enrique
 */
public class CotizacionRegistrarPanel extends javax.swing.JPanel {

    Cliente c = new Cliente();
    CotizacionTableModel myTableModel;
    private JDialog parent;
    Date fecha = new Date ();
    SimpleDateFormat formatFecha = new SimpleDateFormat("dd/MM/yyyy");
    int numero = GestionVentas.getInstance().getCorrelativoCotizacion();
    long maximo = GestionConfiguracion.getInstance().getCantMaxPedido();
    private CotizacionMainPanel refSalesPanel;
    ArrayList<LineaCotizacion> lineas = new ArrayList<>();
    
    //Formato decimal
    DecimalFormatSymbols simbolos = new DecimalFormatSymbols();
    DecimalFormat df; 
    
    public void setParent(JDialog parent){
        this.parent = parent;
    }
    
    public void setRefSalesPanel(CotizacionMainPanel panel){
        this.refSalesPanel = panel;
    }
        
    class CotizacionTableModel extends AbstractTableModel{
        String [] titles = {"Linea de Documento", "Producto","Precio Unitario",
                            "Cantidad","SubTotal"};

        @Override
        public int getRowCount() {
            return lineas.size();
        }

        @Override
        public int getColumnCount() {
            return titles.length;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            String res=null;
            LineaCotizacion lpc = lineas.get(rowIndex);
            switch(columnIndex){
                case 0: res = lpc.getNumLinea()+""; break;
                case 1: res = lpc.getNombre();break;
                case 2: res = lpc.getPrecioUnitario()+""; break;
                case 3: res = lpc.getCantidad()+"";break;
                case 4: res = df.format(lpc.getSubTotal()); break;
            }
            return res;
        }
        
        @Override
        public boolean isCellEditable(int row, int col) {
            if (col == 2 || col ==3){
                return true;
            } else {
                return false;
            }
        }
        
        @Override
        public void setValueAt(Object value,  int row, int col){
            LineaCotizacion lipr = lineas.get(row);
            if(col==2){
                double precioU = Double.parseDouble(value.toString());
                lipr.setPrecioUnitario(precioU);
                lipr.setSubTotal(GestionVentas.getInstance().Redondear(lipr.getCantidad()*precioU));            
                refreshItemsTable();
            }
            else{                
                int cantidad = Integer.parseInt(value.toString());
                lipr.setCantidad(cantidad);
                lipr.setSubTotal(GestionVentas.getInstance().Redondear(cantidad*lipr.getPrecioUnitario()));            
                refreshItemsTable();
            }
        }
        
        @Override
        public String getColumnName(int col){
            return titles[col];
        }
    }
    
    public CotizacionRegistrarPanel() {
        initComponents();
        txtNombre.setEnabled(false);
        txtNumDoc.setEnabled(false);
        txtNumCotizacion.setEnabled(false);
        dpFecha.setEnabled(false);
        txtMontoTotal.setEnabled(false);
        dpFecha.setDate(fecha);
        txtNumCotizacion.setText(numero+"");
        
        this.simbolos.setDecimalSeparator('.');
        this.df = new DecimalFormat("#.00",simbolos);
        
        Calendar calendar = dpFechaVen.getMonthView().getCalendar();
        calendar.setTime(new Date());
        dpFechaVen.getMonthView().setLowerBound(calendar.getTime());
        
        myTableModel = new CotizacionTableModel();
        tblProductos.setModel(myTableModel);
        TableRowSorter<CotizacionTableModel> sorter = new TableRowSorter<> ((CotizacionTableModel) tblProductos.getModel());
        tblProductos.setRowSorter(sorter);
    }

    public void llenaCliente(){
        txtNombre.setText((c.getRazonSocial()!=null)?c.getRazonSocial():(c.getApePaterno()+" "+c.getApeMaterno()+", "+c.getNombres()));
        txtNumDoc.setText(c.getNumDocumento());        
    }
    
    public void refreshItemsTable(){
        double montoSoles = 0;
        for(int i=0;i<lineas.size();i++){
            montoSoles=montoSoles+lineas.get(i).getSubTotal();
        }
        txtMontoTotal.setText(df.format(GestionVentas.getInstance().Redondear(montoSoles)));
        myTableModel.fireTableChanged(null);        
    }
    
    public void agregaLineaVenta(LineaCotizacion linea){
        Boolean esta=false;
        int i;
        for (i=0;i<lineas.size();i++){
            if(linea.getIdProducto().equals(lineas.get(i).getIdProducto())){
                esta=true;
                break;
            }
        }
        if(!esta)
            lineas.add(linea);            
    }
    
    public void actualizaNumero(){
        for(int i=0;i<lineas.size();i++){
            lineas.get(i).setNumLinea(i+1);
        }
    }
    
    public boolean valido(){
        boolean b = true;
        for(int i=0;i<lineas.size();i++){
            if(lineas.get(i).getCantidad()==0){
                return false;                
            }
        }
        return b;
    }

    public boolean maximoValido(){
        for(int i=0;i<lineas.size();i++){
            if(lineas.get(i).getCantidad()>maximo)
                return false;
        }
        return true;
    }
                
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tblProductos = new javax.swing.JTable();
        jPanel3 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtNombre = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtNumDoc = new javax.swing.JTextField();
        btnCliente = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel10 = new javax.swing.JLabel();
        txtNumCotizacion = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        dpFecha = new org.jdesktop.swingx.JXDatePicker();
        jLabel4 = new javax.swing.JLabel();
        txtMontoTotal = new javax.swing.JTextField();
        dpFechaVen = new org.jdesktop.swingx.JXDatePicker();
        jLabel5 = new javax.swing.JLabel();
        btnAnhadir = new javax.swing.JButton();
        btnRegistrar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();

        setMaximumSize(new java.awt.Dimension(784, 549));
        setMinimumSize(new java.awt.Dimension(784, 549));
        setPreferredSize(new java.awt.Dimension(784, 549));

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Lista de Productos"));
        jPanel1.setToolTipText("");
        jPanel1.setMaximumSize(new java.awt.Dimension(1764, 1325));
        jPanel1.setMinimumSize(new java.awt.Dimension(0, 0));
        jPanel1.setPreferredSize(new java.awt.Dimension(764, 319));
        jPanel1.setLayout(new java.awt.BorderLayout());

        tblProductos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tblProductos.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tblProductosKeyPressed(evt);
            }
        });
        jScrollPane2.setViewportView(tblProductos);

        jPanel1.add(jScrollPane2, java.awt.BorderLayout.CENTER);

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Información del Cliente"));

        jLabel1.setText("Razón Social/Nombre");

        jLabel2.setText("Número de Documento");

        btnCliente.setText("Seleccionar Cliente");
        btnCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnClienteActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(18, 43, Short.MAX_VALUE)
                        .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(txtNumDoc, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNumDoc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnCliente)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Información de la Cotización"));

        jLabel10.setText("Núm. de Cotización");

        jLabel3.setText("Fecha");

        jLabel4.setText("Monto Total Soles");

        jLabel5.setText("Fecha de Vencimiento");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jLabel3)
                        .addComponent(jLabel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtMontoTotal, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(dpFecha, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE)
                    .addComponent(txtNumCotizacion, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(dpFechaVen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel10)
                    .addComponent(txtNumCotizacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(dpFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtMontoTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(dpFechaVen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        btnAnhadir.setText("Añadir Producto");
        btnAnhadir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAnhadirActionPerformed(evt);
            }
        });

        btnRegistrar.setText("Registrar");
        btnRegistrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRegistrarActionPerformed(evt);
            }
        });

        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnAnhadir)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnRegistrar)
                        .addGap(18, 18, 18)
                        .addComponent(btnCancelar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(12, 12, 12)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnRegistrar)
                    .addComponent(btnCancelar)
                    .addComponent(btnAnhadir))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnRegistrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRegistrarActionPerformed
        if(!txtNumDoc.getText().isEmpty()){
            if(lineas.isEmpty())
                JOptionPane.showMessageDialog(this,"Debe seleccionar, por lo menos, un producto.");
            else {
                if(valido()){
                    if(maximoValido()){
                        if(dpFechaVen.getDate()!=null){
                            String idCliente = c.getIdCliente();
                            double totalSoles = Double.parseDouble(txtMontoTotal.getText());
                            String codigo = GestionVentas.getInstance().getCodCotizacion(); 
                            Date fechaVen = dpFechaVen.getDate();

                            Cotizacion cotizacion = new Cotizacion(codigo,idCliente,numero,fecha,fechaVen,totalSoles,"Registrado");
                            Controlador.Service.Ventas.GestionVentas.getInstance().registrarCotizacion(cotizacion,lineas);
                            JOptionPane.showMessageDialog(this,"Se registró correctamente la cotización.");
                            refSalesPanel.refreshItemsTable();
                            parent.dispose();
                        }
                        else
                            JOptionPane.showMessageDialog(this,"Debe seleccionar la fecha de vencimiento.");
                    }
                    else
                        JOptionPane.showMessageDialog(this,"Las cantidades no deben exceder el máximo: "+maximo+".");
                }
                else
                    JOptionPane.showMessageDialog(this, "Debe debe completar las cantidades de productos.");
            }
        }
        else
            JOptionPane.showMessageDialog(this,"Debe seleccionar un cliente.");            
    }//GEN-LAST:event_btnRegistrarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        parent.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void btnClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClienteActionPerformed
        ClienteBuscarJDialog buscarCliDialog = new ClienteBuscarJDialog(null, true);
        buscarCliDialog.setRefSalesPanel(this);
        buscarCliDialog.setVisible(true);
    }//GEN-LAST:event_btnClienteActionPerformed

    private void btnAnhadirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAnhadirActionPerformed
        ProductoBuscarJDialog buscarProdDialog = new ProductoBuscarJDialog(null, true);
        buscarProdDialog.setRefPanel(this);
        buscarProdDialog.setVisible(true);
    }//GEN-LAST:event_btnAnhadirActionPerformed

    private void tblProductosKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tblProductosKeyPressed
        if(tblProductos.getSelectedRow()!=-1){
            if(evt.getKeyChar()=='\u007F'){
                int rowSel = tblProductos.getSelectedRow();
                lineas.remove(rowSel);
                actualizaNumero();
                refreshItemsTable();
            } 
        }
    }//GEN-LAST:event_tblProductosKeyPressed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAnhadir;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnCliente;
    private javax.swing.JButton btnRegistrar;
    private org.jdesktop.swingx.JXDatePicker dpFecha;
    private org.jdesktop.swingx.JXDatePicker dpFechaVen;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable tblProductos;
    private javax.swing.JTextField txtMontoTotal;
    private javax.swing.JTextField txtNombre;
    private javax.swing.JTextField txtNumCotizacion;
    private javax.swing.JTextField txtNumDoc;
    // End of variables declaration//GEN-END:variables
}
